package iot.core.springboot;

import iot.core.util.MyJSON;
import org.springframework.core.MethodParameter;
import org.springframework.http.MediaType;
import org.springframework.http.server.ServerHttpRequest;
import org.springframework.http.server.ServerHttpResponse;
import org.springframework.http.server.ServletServerHttpResponse;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.servlet.mvc.method.annotation.ResponseBodyAdvice;

import java.util.HashMap;

@ControllerAdvice(basePackages ="iot")
public class MyResponseBodyAdvice implements ResponseBodyAdvice {

    @Override
    public boolean supports(MethodParameter returnType, Class converterType) {
        return true;
    }

    @Override
    public Object beforeBodyWrite(Object body, MethodParameter returnType, MediaType selectedContentType,
                                  Class selectedConverterType, ServerHttpRequest request, ServerHttpResponse response) {
        var contentType=((ServletServerHttpResponse) response).getServletResponse().getContentType();
        if(StringUtils.hasText(contentType)){
            return  body;
        }

        if(body==null){
            return MyApiResult.other(201,"返回为空","");
        }
        //关键
        if(body  instanceof  MyApiResult){
            return body;
        }
        if(body  instanceof  String){
            return MyJSON.toJSONString( MyApiResult.success(body) );
        }

        if(body  instanceof HashMap){
            HashMap hashMap=(HashMap)body;
            if(hashMap.get("status")!=null
                &&hashMap.get("error")!=null

            ){
                Integer status=(Integer)hashMap.get("status");
                String error=hashMap.get("error").toString();
                return MyApiResult.other(status,error,"");
            }
            return MyJSON.toJSONString( MyApiResult.success(body) );
        }

        return MyApiResult.success(body);
    }

}
